package com.liujie.app.controller;


import com.github.pagehelper.PageInfo;
import com.liujie.app.dto.AppInfoDto;
import com.liujie.app.entity.AppInfo;
import com.liujie.app.entity.AppVersion;
import com.liujie.app.service.AppInfoService;
import com.liujie.app.service.AppInfoVersionService;
import com.liujie.app.utils.SessionUtils;
import com.liujie.app.vo.Result;
import com.liujie.app.vo.TokenVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/appInfo")
@Api(value = "app信息")
public class AppInfoController {

    @Autowired
    AppInfoService appInfoService;
    @Autowired
    AppInfoVersionService appInfoVersionService;

    @PostMapping("/page")
    @ApiOperation(value = "分页查询app信息",notes = "分页查询app信息")
    public Result getPage(@RequestBody AppInfoDto appInfoDto, @RequestParam(defaultValue = "1") Integer pageNum) {
        PageInfo<AppInfo> pageInfo = appInfoService.getPage(appInfoDto, pageNum);
        if (pageNum > pageInfo.getPages()){
            pageInfo.setPageNum(1);
            pageInfo = appInfoService.getPage(appInfoDto, pageInfo.getPageNum());
        }
        return Result.success(pageInfo);
    }

    @PostMapping("/insertOrUpdate")
    @ApiOperation(value = "新增、修改app信息",notes = "新增、修改app信息")
    public Result insertOrUpdate(AppInfo appInfo, MultipartFile file, HttpServletRequest request) {
        if (file !=null && !file.isEmpty()) {
            String realPath = request.getServletContext().getRealPath("upload/");
            String filename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(filename);
            if (file.getSize() > 512000) {
                return Result.error("图片大于500kb");
            } else if (extension.equalsIgnoreCase("gif") || extension.equalsIgnoreCase("jpeg") ||
                    extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("jpg")) {
                filename = UUID.randomUUID().toString().replace("-", "") + "." + extension;
                File save = new File(realPath);
                if (!save.exists()) {
                    save.mkdirs();
                }
                try {
                    file.transferTo(new File(realPath + File.separator + filename));
                    appInfo.setLogopicpath("/upload/" + filename);
                } catch (IOException e) {
                    e.printStackTrace();
                    return Result.error("文件异常");
                }

            } else {
                return Result.error("文件格式不正确");
            }
        } else if (appInfo.getId() == null) {
            return Result.error("文件必填");
        }



        String token = request.getHeader("token");
        TokenVo tokenVo = (TokenVo) SessionUtils.get(token);
        if (appInfo.getId() == null) {
            appInfo.setStatus(1L);
            appInfo.setCreatedby(2L);
            appInfo.setDevid(tokenVo.getId());
            appInfo.setCreationdate(new Date());
        } else {
            appInfo.setCreatedby(2L);
            appInfo.setStatus(1L);
            appInfo.setCreationdate(new Date());
        }
            return appInfoService.getInsertOrUpdate(appInfo);
    }

    @GetMapping("/selApkName")
    @ApiOperation(value = "验证阿apk唯一性",notes = "验证阿apk唯一性")
    public Result selApkName(String apkname) {
        int i = appInfoService.getApkName(apkname);
        return Result.success(i);
    }

    @PostMapping("/selAppInfo")
    @ApiOperation(value = "根据id查找app信息",notes = "根据id查找app信息")
    public Result selAppInfo(Integer id) {
        AppInfo appInfo = appInfoService.getSelAppInfo(id);
        return Result.success(appInfo);
    }

    @PutMapping("/updateStatus/{status}/{id}")
    @ApiOperation(value = "修改所属状态",notes = "修改所属状态")
    public Result updateStatus(@PathVariable String status, @PathVariable Integer id) {
        int updateStatus = appInfoService.getUpdateStatus(id, status);
        if (updateStatus > 0) {
            return Result.success();
        } else {
            return Result.error("操作失败");
        }
    }

    @DeleteMapping("/deleteAppInfo")
    @ApiOperation(value = "根据id删除app信息",notes = "根据id删除app信息")
    public Result deleteAppInfo(Integer id, HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("");
        AppInfo selAppInfo = appInfoService.getSelAppInfo(id);
        new File(realPath + File.separator + selAppInfo.getLogopicpath()).delete();
        appInfoVersionService.getDelete(id);
        int delete = appInfoService.getDelete(id);
        if (delete > 0) {
            return Result.success(delete);
        } else {
            return Result.error("操作失败");
        }
    }

    @GetMapping("/selVersion")
    @ApiOperation(value = "查看版本信息",notes = "查看版本信息")
    public Result selVersion(Integer appid) {
        List<AppVersion> selVersion = appInfoVersionService.getSelVersion(appid);
        return Result.success(selVersion);
    }

    @PostMapping("/insertVersion")
    @ApiOperation(value = "新增版本信息",notes = "新增版本信息")
    public Result insertVersion(AppVersion appVersion, MultipartFile file, HttpServletRequest request) {
        if (file!=null && !file.isEmpty()) {
            String realPath = request.getServletContext().getRealPath("upload/apk");
            String filename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(filename);
            if (file.getSize() > 512000) {
                return Result.error("文件大于500kb");
            } else if (extension.equalsIgnoreCase("apk")) {
                filename = UUID.randomUUID().toString().replace("-", "") + "." + extension;
                File save = new File(realPath);
                if (!save.exists()) {
                    save.mkdirs();
                }
                try {
                    file.transferTo(new File(realPath + File.separator + filename));
                    appVersion.setDownloadlink("/upload/apk/" + filename);
                } catch (IOException e) {
                    e.printStackTrace();
                    return Result.error("文件异常");
                }

            } else {
                return Result.error("文件格式不正确");
            }
        } else {
            return Result.error("apk必填");
        }
        appVersion.setCreationdate(new Date());
        appVersion.setCreatedby(2L);
        appInfoVersionService.getInsert(appVersion);

        AppInfo appInfo=new AppInfo();
        appInfo.setId(appVersion.getAppid());
        appInfo.setVersionid(appVersion.getId());
        appInfo.setCreatedby(appVersion.getAppid());
        appInfo.setStatus(1L);
        appInfo.setCreationdate(new Date());
        appInfoService.getInsertOrUpdate(appInfo);
        return Result.success();
    }
    @GetMapping("/selVersionYi")
    public Result selVersionYi(Integer appid){
        List<AppVersion> selVersionYi = appInfoVersionService.getSelVersionYi(appid);
        return Result.success(selVersionYi);
    }
}
